/*
    Copyright (C) 2021 Huawei Device Co., Ltd.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.danikula.videocache.onefileStrategy;

import com.danikula.videocache.*;
import com.danikula.videocache.bean.ProgressBean;
import com.danikula.videocache.interfacers.CacheListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.util.ArrayList;
import java.util.List;

/**
 * 分节点缓存策略
 */
public class OneFileCacheStrategy extends CacheStrategy {
    private final DatabaseHelper preferences;

    public OneFileCacheStrategy(Context context) {
        this.preferences = new DatabaseHelper(context);
    }

    /**
     * 每次打开APP获取分节点存储的区域
     * 用于初始化显示当前视频已经缓存的区域
     *
     * @param cacheVideoUrl 处理过的视频url
     * @return 分段显示进度条的进度值
     */
    public List<ProgressBean> getInitSpData(String cacheVideoUrl) {
        // 先初始化自定义分段显示进度条0-100的数值
        List<ProgressBean> initData = new ArrayList<>();
        for (int i = 0; i <= 100; i++) {
            ProgressBean bean = new ProgressBean();
            bean.setDefault(true);
            bean.setProgress(i);
            initData.add(bean);
        }
        List<long[]> downLoadArea = new ArrayList<>();
        if (preferences == null || TextTool.isNullOrEmpty(cacheVideoUrl)) {
            return initData;
        }
        Preferences pre = this.preferences.getPreferences(cacheVideoUrl);
        String gson = pre.getString(Constants.VIDEO_CACHE_SP, "");
        long fileLength = pre.getLong(Constants.CACHE_FILE_LENGTH, 0);
        if (fileLength <= 0 || TextTool.isNullOrEmpty(gson)) {
            return initData;
        }
        // 再从Preferences里面获取缓存的进度范围
        long[][] caches = new Gson().fromJson(gson, new TypeToken<long[][]>() {
        }.getType());
        if (caches == null) {
            return initData;
        }
        for (int i = 0; i < caches.length; i++) {
            long[] longs = caches[i];
            if (longs[0] != longs[1]) {
                downLoadArea.add(longs);
            }
        }
        transDownloadAreaToProgress(fileLength, downLoadArea, initData);
        return initData;
    }


    @Override
    protected ProxyCache createHttpProxyCache(HttpUrlSource source, Config config, CacheListener uiCacheListener,
    String url) throws ProxyCacheException {
        OneFileCache cache = new OneFileCache(generateCacheFile(config, url), config.diskUsage);
        Preferences cacheSp = this.preferences.getPreferences(Config.generateCacheName(url));
        cache.setPreferences(cacheSp);
        OneFileProxyCache oneFileProxyCache = new OneFileProxyCache(source, cache);
        oneFileProxyCache.registerCacheListener(uiCacheListener);
        return oneFileProxyCache;
    }
}
